package com.ldy.transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

/**
 * Student服务类<br>
 * 版权: Copyright (c) 2011-2018<br>
 * 公司: 活力天汇<br>
 *
 * @author: 刘德咏<br>
 * @date: 2018-07-23<br>
 */
public class StudentService {
    private Logger logger = LoggerFactory.getLogger(StudentService.class);

    public StudentDao studentDao;

    @Transactional
    // 不抓异常是否回滚
    public void saveNoCatch() {
        StudentEntity studentEntity1 = new StudentEntity(1, "stu1", 18);
        studentDao.save(studentEntity1);
        // 打断点，然后让数据库服务器关机  name 字段有唯一索引
        StudentEntity studentEntity2 = new StudentEntity(2, "stu1", 20);
        studentDao.save(studentEntity2);
    }

    @Transactional
    // 不抓异常是否回滚
    public void saveCatch() {
        try {
            StudentEntity studentEntity1 = new StudentEntity(1, "stu1", 18);
            studentDao.save(studentEntity1);
            // 打断点，然后让数据库服务器关机
            StudentEntity studentEntity2 = new StudentEntity(2, "stu1", 20);
            studentDao.save(studentEntity2);
        } catch (Exception e) {
            logger.error("吞异常是否回滚{}", e);
        }
    }

    @Transactional
    // 不抓异常是否回滚
    public void saveCatchthrowRuntimeException() {
        try {
            StudentEntity studentEntity1 = new StudentEntity(1, "stu1", 18);
            studentDao.save(studentEntity1);
            // 打断点，然后让数据库服务器关机
            StudentEntity studentEntity2 = new StudentEntity(2, "stu1", 20);
            studentDao.save(studentEntity2);
        } catch (Exception e) {
            logger.error("吞异常是否回滚{}", e);
            throw new RuntimeException("插入学生失败");
        }
    }

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }
}
